package socketVersion;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.LinkedList;

public class GenericClient {
	private String ip;
	private int port;
	
	public GenericClient(String ip, int port){
		this.ip = ip;
		this.port = port;
	}
	
	public Reply sendRequest(Request request){
		Socket connection;
		ObjectOutputStream out;
		ObjectInputStream in;
		Reply reply;
		
		try {
			connection = new Socket(ip,port);
			out = new ObjectOutputStream(connection.getOutputStream());
			in = new ObjectInputStream(connection.getInputStream());
			out.writeObject(request);
			reply = (Reply)in.readObject();
			out.close();
			in.close();
			connection.close();
		} catch (IOException e1) {
			System.err.println("IO Error sending request: " + request.getMethodName() + "," + request.getArgs().toString());
			return new Reply(Reply.STATUS_IO_ERROR, new LinkedList<Object>());
		} catch (ClassNotFoundException e) {
			System.err.println("Server Error sending request: " + request.getMethodName() + "," + request.getArgs().toString());
			return new Reply(Reply.STATUS_SERVER_ERROR, new LinkedList<Object>());
		}
		return reply;
		
	}
}
